package com.study.ceph.connection;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 连接构造器
 */
@Slf4j
public class CephUtil {

    public static AmazonS3 getConnection(String accessKey, String secretKey, String endpoint, String signer, String signing) {
        BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setSignerOverride(signer);
        //访问协议
        clientConfig.setProtocol(Protocol.HTTP);

        return AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withClientConfiguration(clientConfig)
                .withEndpointConfiguration(
                        //设置要用于请求的端点配置（服务端点和签名区域）
                        new AwsClientBuilder.EndpointConfiguration(
                                endpoint,
                                signing))
                //是否使用路径方式，是的话s3.xxx.sn/bucketname
                .withPathStyleAccessEnabled(true)
                .build();
    }


    /**
     * ceph文件上传
     *
     * @param bucketName ceph bucket
     * @param path       文件目录
     * @param fileBytes  文件字节码
     * @return
     */
    public static boolean upload(AmazonS3 conn, String bucketName, String path, byte[] fileBytes) {
        if (null == conn) {
            throw new RuntimeException("未能获取到ceph连接");
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileBytes);
        try {
            PutObjectResult putObjectResult = conn.putObject(bucketName, path, byteArrayInputStream, new ObjectMetadata());
        } catch (Exception e) {
            log.error("上传文件到ceph失败：{}", e);
            return false;
        }
        stopWatch.stop();
        log.info("ceph文件上传耗时：{}ms", stopWatch.getTotalTimeMillis());
        return true;
    }


    /**
     * ceph文件下载
     *
     * @param conn         ceph连接
     * @param bucketName   ceph bucket
     * @param path         文件路径
     * @param outputStream 文件输出流
     * @return
     */
    public static String download(AmazonS3 conn, String bucketName, String path, OutputStream outputStream) {
        if (null == conn) {
            throw new RuntimeException("未能获取到ceph连接");
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        S3Object object = conn.getObject(bucketName, path);

        try (S3ObjectInputStream objectContent = object.getObjectContent();
             InputStream inputStream = objectContent.getDelegateStream();) {
            byte[] cache = new byte[1024];
            int lenth = -1;
            while ((lenth = inputStream.read(cache)) != -1) {
                outputStream.write(cache, 0, lenth);
            }
        } catch (Exception e) {
            log.error("文件下载异常：{}ms", e);
            return null;
        }
        stopWatch.stop();
        log.info("ceph文件下载耗时：{}", stopWatch.getTotalTimeMillis());
        return object.getKey();
    }

}
